<template>
  <div class="chart-card">
    <div class="card-header">
      <h3 class="card-title">{{ title }}</h3>
      <div class="year-selector" v-if="showYearSelector">
        <el-select v-model="selectedYear" size="small" placeholder="选择年份">
          <el-option
            v-for="year in availableYears"
            :key="year"
            :label="year + '年'"
            :value="year"
          >
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="card-content">
      <div ref="chartContainer" class="chart-container"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  title: {
    type: String,
    default: '活跃度热图'
  },
  data: {
    type: Array,
    default: () => []
  },
  showYearSelector: {
    type: Boolean,
    default: true
  }
})

const chartContainer = ref(null)
let chart = null

const currentYear = new Date().getFullYear()
const selectedYear = ref(currentYear)
const availableYears = [currentYear - 1, currentYear, currentYear + 1]

// 生成模拟数据
const generateDemoData = () => {
  const startDate = new Date(selectedYear.value, 0, 1)
  const endDate = new Date(selectedYear.value, 11, 31)
  
  const data = []
  let i = 0
  const dateTime = startDate.getTime()
  
  while (startDate.getTime() <= endDate.getTime()) {
    const value = Math.floor(Math.random() * 10)
    data.push([
      echarts.format.formatTime('yyyy-MM-dd', startDate),
      value
    ])
    startDate.setDate(startDate.getDate() + 1)
    i++
  }
  
  return data
}

const chartData = computed(() => {
  if (props.data.length > 0) {
    return props.data
  }
  return generateDemoData()
})

const initChart = () => {
  if (!chartContainer.value) return
  
  // 设置图表选项
  const option = {
    tooltip: {
      position: 'top',
      formatter: function (p) {
        return p.data[0] + ': ' + p.data[1] + ' 活跃度'
      }
    },
    visualMap: {
      min: 0,
      max: 10,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: '0%',
      inRange: {
        color: ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127']
      }
    },
    calendar: {
      top: 30,
      left: 50,
      right: 10,
      cellSize: ['auto', 15],
      range: String(selectedYear.value),
      itemStyle: {
        borderWidth: 0.5,
        borderColor: '#fff'
      },
      yearLabel: { show: false }
    },
    series: {
      type: 'heatmap',
      coordinateSystem: 'calendar',
      data: chartData.value
    }
  }

  // 如果图表已经存在，销毁它
  if (chart) {
    chart.dispose()
  }
  
  // 创建图表实例
  chart = echarts.init(chartContainer.value)
  // 应用选项
  chart.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', handleResize)
}

const handleResize = () => {
  if (chart) {
    chart.resize()
  }
}

// 监听年份变化
watch(() => selectedYear.value, () => {
  if (chart) {
    chart.setOption({
      calendar: {
        range: String(selectedYear.value)
      },
      series: {
        data: chartData.value
      }
    })
  }
})

// 监听数据变化
watch(() => props.data, () => {
  if (chart) {
    chart.setOption({
      series: {
        data: chartData.value
      }
    })
  }
}, { deep: true })

onMounted(() => {
  initChart()
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (chart) {
    chart.dispose()
    chart = null
  }
})
</script>

<style scoped>
.chart-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2329;
  margin: 0;
}

.year-selector {
  width: 100px;
}

.card-content {
  flex: 1;
  min-height: 200px;
}

.chart-container {
  width: 100%;
  height: 100%;
  min-height: 200px;
}
</style> 